#include "UDP.h"
#include "Main/GateWay.h"
UDP::UDP(QObject *parent)
    : BasePort(parent)
{
//    qDebug()<<"Connect UDP SLOT now------------------------------";
    udp = new QUdpSocket(this);
    connect(udp,SIGNAL(readyRead()),this,SLOT(readyReadSlot()));
}

void UDP::setPortParam(PortStruct portParam)
{
    m_portParam = portParam;
    this->setObjectName(portParam.name());
}

void UDP::open()
{
    udp->bind(m_portParam.port(),QUdpSocket::ShareAddress);
}

void UDP::close()
{
    udp->close();
}

void UDP::write(PortStruct target, QByteArray data)
{
    QString time = QDateTime::currentDateTime().toString("yyyy-MM-dd");
    udp->writeDatagram(data,(QHostAddress)target.ip(),target.port());
    qDebug()<<"Write-->"<<target<<"data:"<<DataTypeConver::formatString(data);

    Log::lock.lockForWrite();
    Log::writeToLog(time,"Write-->"+target.name()+" data: "+DataTypeConver::formatString(data));
    Log::lock.unlock();

}



/*********************************************
* @Name        slot_ReadData
* @Funcyion    接收槽函数
* @Param       NONE
* @Return      NONE
* @Other       槽函数
*********************************************/
void UDP::readyReadSlot()
{
    if(udp->hasPendingDatagrams())  //拥有等待的数据报
    {
         QString time = QDateTime::currentDateTime().toString("yyyy-MM-dd");
        QByteArray data;
        QHostAddress ip;
        quint16 port;
        data.resize(udp->pendingDatagramSize()); //把datagram的size归一化到参数size的大小一样
        udp->readDatagram(data.data(), data.size(), &ip, &port);  //接收数据报，将其存放到datagram中

        PortStruct source;
        source.setType(m_portParam.type());
        source.setName(this->objectName());
        source.setIp(ip.toString());
        source.setPort(port);
        m_portParam.setIp(ip.toString());
        m_portParam.setPort(port);
        if((data.at(0)==0x53)&&(data.at(1)==0x63))  //ScanRequest
        {
            return;
        }
       // qDebug()<<"Read<-- "<<source<<"data:"<<DataTypeConver::formatString(data);
        qDebug()<<"Read<-- "<<source<<"data:"<<data.data();
         qDebug()<<"Read<-- "<<m_portParam<<"data:"<<data.data();
        {
            QString str;
            for(int i=0;i<data.size();i++)
            {
                str+=QString("%1").arg((unsigned char)data.at(i),2,16,QLatin1Char('0'))+' ';
            }
            qDebug()<<str;  //打印十六进制数据
        }


        if((data.at(0)!=0x53)||(data.at(1)!=0x63))
        {
        Log::lock.lockForWrite();

        Log::writeToLog(time,"Read<--"+m_portParam.name()+" data: "+DataTypeConver::formatString(data));
        Log::lock.unlock();
        }

         qDebug()<<"UDP::readyReadSlot before emit receiveDataSignal----- ";
       // emit receiveDataSignal(source,data);
       //  QEventLoop loop;//定义一个新的事件循环

         emit receiveDataSignal(m_portParam,data);
       //  loop.exec();

    }
}


UDP::~UDP()
{

}
